#include <iostream>
#include <sys/socket.h>
#include <netinet/in.h>
#include <unistd.h>
#include <arpa/inet.h>
#include "Commn.hpp"
#include "Log.hpp"

#include <string>

using namespace LogModule;

//./clent ip + port
int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        Usage();
    }
    // 创建socket
    int socketfd = ::socket(AF_INET, SOCK_STREAM, 0);
    if (socketfd < 0)
    {
        LOG(LogLevel::ERROR) << "创建socket失败!";
        return 1;
    }
    LOG(LogLevel::INFO) << "socketfd create success is: " << socketfd;
    uint16_t port = std::stoi(argv[2]);
    struct sockaddr_in server;
    server.sin_family = AF_INET;
    server.sin_addr.s_addr = ::inet_addr(argv[1]); //网络转主机序列
    server.sin_port = ::htons(port); //网络转主机序列
    socklen_t len = sizeof(server);
    
    int n = ::connect(socketfd, CONV(&server), len);
    if (n < 0)
    {
        LOG(LogLevel::ERROR) << "connect error";
        return 2;
    }
    LOG(LogLevel::INFO) << "connect  success ";
    std::string message;
    while (true)
    {
        std::cout << "Please input message: ";
        std::getline(std::cin, message);
        std::cout << message << std::endl;
        std::cout << message.size() << std::endl;
        ssize_t n = ::send(socketfd, message.c_str(), message.size(), 0);
        if (n >= 0)
        {
            char inbuffer[1024];
            ssize_t n1 = recv(socketfd, inbuffer, sizeof(inbuffer) - 1, 0);
            if (n > 0)
            {
                inbuffer[n1] = 0;
                LOG(LogLevel::INFO) << "echo server: " << inbuffer;
            }
        }
        else
        {
            LOG(LogLevel::WARNING) << "发送失败";
        }
    }
    ::close(socketfd);
    return 0;
}